package ca.ubc.cpsc210.waldo.waldowebservice;

//import WaldoService;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import ca.ubc.cpsc210.waldo.exceptions.WaldoException;
import ca.ubc.cpsc210.waldo.model.Waldo;
import ca.ubc.cpsc210.waldo.util.LatLon;

public class WaldoService {

	private final static String WALDO_WEB_SERVICE_URL = "http://kramer.nss.cs.ubc.ca:8080/";

	private String key;
	
	/**
	 * Constructor
	 */
	public WaldoService() {
	}

	/**
	 * Initialize a session with the Waldo web service. The session can time out
	 * even while the app is active...
	 * 
	 * @param nameToUse
	 *            The name to go register, can be null if you want Waldo to
	 *            generate a name
	 * @return The name that Waldo gave you
	 */
	public String initSession(String nameToUse) {
		// CPSC 210 Students. You will need to complete this method
		StringBuilder urlBuilder = new StringBuilder(WALDO_WEB_SERVICE_URL);
		
		if (nameToUse == null)
			urlBuilder.append("initsession/");
		else
			urlBuilder.append("initsession/" + nameToUse);
		
		// Print check URL
//		System.out.println(urlBuilder);
		
		// Make the request
		InputStream in = null;
		try {
			JSONObject obj;
			String s = makeJSONQuery(urlBuilder);
//			System.out.println(s);
			
			obj = (JSONObject) new JSONTokener(s).nextValue();
//			System.out.println(obj);
			
			key = (String) obj.get("Key");
			
			return (String) obj.get("Name");
			
		} catch (Exception e) {
			// Return an empty set of bus stops but let developer know
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Get waldos from the Waldo web service.
	 * 
	 * @param numberToGenerate
	 *            The number of Waldos to try to retrieve
	 * @return Waldo objects based on information returned from the Waldo web
	 *         service
	 */
	public List<Waldo> getRandomWaldos(int numberToGenerate) {
		// CPSC 210 Students: You will need to complete this method
		
		StringBuilder urlBuilder = new StringBuilder(WALDO_WEB_SERVICE_URL);
		
		urlBuilder.append("getwaldos/" + key +  "/" + numberToGenerate);
		
		// Print check URL
//		System.out.println(urlBuilder);
		
		// Make the request
		InputStream in = null;
		try {
			JSONArray arr;
			String s = makeJSONQuery(urlBuilder);
//			System.out.println(s);
			
			arr = (JSONArray) new JSONTokener(s).nextValue();
//			System.out.println(arr);
			
			JSONObject obj;
			JSONObject objLoc;
			
			String name;
			double lat, lon;
			int tStamp;
			List<Waldo> waldos = new ArrayList<Waldo>();
			int i;
			
			for (i = 0; i < arr.length(); i++) {
				obj = arr.getJSONObject(i);
				name = (String) obj.get("Name");
				
				objLoc = obj.getJSONObject("Loc");
				
				lat = objLoc.getDouble("Lat");
				lon = objLoc.getDouble("Long");
				tStamp = objLoc.getInt("Tstamp");
				
				waldos.add(new Waldo(name, new Date(tStamp), new LatLon(lat, lon)));
				
				// NOTE: The fields of the Waldo class have been set to public for easy access.
				System.out.println("Name: " +waldos.get(i).name + " | Lat: " + waldos.get(i).lastLocation.getLatitude() + " | Lon: " + waldos.get(i).lastLocation.getLongitude() + " | tStamp: " + waldos.get(i).lastUpdated.getTime());
			}
			
			return waldos;
			
		} catch (Exception e) {
			// Return an empty set of bus stops but let developer know
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * Return the current list of Waldos that have been retrieved
	 * 
	 * @return The current Waldos
	 */
	public List<Waldo> getWaldos() {
		// CPSC 210 Students: You will need to complete this method
		return null;
	}

	/**
	 * Retrieve messages available for the user from the Waldo web service
	 * 
	 * @return A list of messages
	 */
	public List<String> getMessages() {
		// CPSC 210 Students: You will need to complete this method
		return null;
	}
	
	/**
	 * Execute a given query 
	 * 
	 * @param urlBuilder The query with everything
	 * @return The JSON returned from the query 
	 */
	private String makeJSONQuery(StringBuilder urlBuilder) {
		try {
			URL url = new URL(urlBuilder.toString());
			HttpURLConnection client = (HttpURLConnection) url.openConnection();
			client.setRequestProperty("accept", "application/json");
			InputStream in = client.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String returnString = br.readLine();
			client.disconnect();
			return returnString;
		} catch (Exception e) {
			throw new WaldoException("Unable to make JSON query: " + urlBuilder.toString());
		}
	}

	public static void main(String[] args) {
		WaldoService ws1 = new WaldoService();
		ws1.initSession(null);
		ws1.getRandomWaldos(5);
		
		
		
	}
}
